package com.example.demo.multidatasource;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/5 0005.
 */
@Component
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static Map<Object, Object> dsMap;

    // 初始化数据库
    static {
        dsMap = new HashMap<Object, Object>();
        Class<? extends DataSource> dataSourceType = null;
        try {
            dataSourceType = (Class<? extends DataSource>) Class
                    .forName("com.alibaba.druid.pool.DruidDataSource");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String driverClassName = "org.postgresql.Driver";
        String url = "jdbc:postgresql://localhost:5432/cjk";
        String username = "postgres";
        String password = "123456";
        DataSource dataSource = DataSourceBuilder.create().type(dataSourceType).driverClassName
                (driverClassName).url(url)
                .username(username).password(password).build();
        dsMap.put(1L, dataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceKey();
    }

    @Override
    public void afterPropertiesSet() {
        try {
            initDataSource();
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.afterPropertiesSet();
    }

    private void initDataSource() {
        super.setTargetDataSources(dsMap);
        DynamicDataSourceContextHolder.setDataSourceKey(1L);
        setDefaultTargetDataSource(dsMap.get(1L)); //设置默认数据源
    }

    public void addDataSource(Long dsKey) {
        if (!dsMap.containsKey(dsKey)) {
            DataSource dataSource = this.newDataSource(dsKey);
            dsMap.put(dsKey, dataSource);
        }
        super.setTargetDataSources(dsMap);
        //重点
        super.afterPropertiesSet();
    }

    private DataSource newDataSource(Long dsKey) {
        this.logger.info("Build Data Source...");
        // 根据HTTP接口获取数据源配置信息
        Map<String, Object> dataSourceMap = this.getDataSourceConfigure(dsKey);
        DataSource dataSource = this.buildDataSource(dataSourceMap);
        if (null != dataSource) {
            return dataSource;
        }
        throw new RuntimeException("新建数据源失败");
    }

    private DataSource buildDataSource(Map<String, Object> dataSourceMap) {
        try {
            Class<? extends DataSource> dataSourceType = (Class<? extends DataSource>) Class
                    .forName("com.alibaba.druid.pool.DruidDataSource");
            String driverClassName = dataSourceMap.get("driver-class-name").toString();
            String url = dataSourceMap.get("url").toString();
            String username = dataSourceMap.get("username").toString();
            String password = dataSourceMap.get("password").toString();
            return DataSourceBuilder.create().type(dataSourceType).driverClassName
                    (driverClassName).url(url)
                    .username(username).password(password).build();
        } catch (ClassNotFoundException e) {
            logger.error("创建数据源失败：{}", e);
            return null;
        }
    }

    private Map<String, Object> getDataSourceConfigure(Long dataSourceKey) {
        Map<String, Object> configureMap = new HashMap<>();
        if (dataSourceKey == null) {
            configureMap.put("url", "jdbc:postgresql://localhost:5432/cjk");
            configureMap.put("username", "postgres");
            configureMap.put("password", "123456");
            configureMap.put("driver-class-name", "org.postgresql.Driver");
        } else {
            if (dataSourceKey.compareTo(new Long(1L)) == 0) {
                configureMap.put("url", "jdbc:postgresql://localhost:5432/cjk");
                configureMap.put("username", "postgres");
                configureMap.put("password", "123456");
                configureMap.put("driver-class-name", "org.postgresql.Driver");
            } else {
                configureMap.put("url", "jdbc:postgresql://localhost:5432/test");
                configureMap.put("username", "postgres");
                configureMap.put("password", "123456");
                configureMap.put("driver-class-name", "org.postgresql.Driver");
            }

        }
        return configureMap;
    }
}
